package com.ywy.templates;

import com.ywy.common.templates.DirectiveHandler;
import com.ywy.common.templates.TemplateDirective;
import com.ywy.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 本周热议自定义标签
 *
 * @author ywy
 * @date 2021/12/24 18:40
 */
@Component
public class HotsTemplate extends TemplateDirective {
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public String getName() {
        return "hots";
    }

    @Override
    public void execute(DirectiveHandler handler) throws Exception {
        String key = "week_rank";
        // 读取本周热议数据
        Set<ZSetOperations.TypedTuple> set = redisUtil.zrevrange(key, 0, 6);

        List<Map<String, Object>> hotPosts = new ArrayList<>();
        for (ZSetOperations.TypedTuple typedTuple : set) {
            Map<String, Object> map = new HashMap<>();
            Object id = typedTuple.getValue();
            map.put("id", id);
            map.put("title", redisUtil.hget("rank_post:" + id, "post:title"));
//            map.put("commentCount", redisUtil.hget("rank_post:" + id, "post:commentCount"));
            map.put("commentCount", typedTuple.getScore());
            hotPosts.add(map);
        }

        handler.put(RESULTS, hotPosts).render();
    }
}
